package com.gzc.just.play.last.war.sceneserver;

import com.gzc.just.play.last.war.common.handler.VirtualThreadNettyServer;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import com.gzc.just.play.last.war.sceneserver.handler.*;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.DependsOn;

/**
 * Scene Server的Netty服务器实现（重构版）
 * 使用虚拟线程处理场景相关请求
 */
@Component("sceneNettyServer")
public class SceneNettyServer extends VirtualThreadNettyServer {
    private static final Logger logger = LoggerFactory.getLogger(SceneNettyServer.class);
    
    @Value("${scene.server.port:50001}")
    private int sceneServerPort;
    
    @Value("${scene.server.host:127.0.0.1}")
    private String sceneServerHost;
    
    @Autowired
    private ApplicationContext applicationContext;
    
    public SceneNettyServer() {
        logger.info("SceneNettyServer bean is being constructed");
    }
    
    @Override
    protected int getNettyPort() {
        return sceneServerPort;
    }
    
    @Override
    protected String getNettyHost() {
        return sceneServerHost;
    }
    
    @Override
    protected VirtualThreadServerFramework.ServerType getServerType() {
        return VirtualThreadServerFramework.ServerType.SCENE_SERVER;
    }
    
    @Override
    protected void initializeHandlers() {
        try {
            // 从Spring容器中获取Bean，而不是直接new
            // 这样可以避免循环依赖问题
            if (applicationContext != null) {
                CreateBattleHandler createBattleHandler = applicationContext.getBean(CreateBattleHandler.class);
                framework.registerHandler(createBattleHandler);
                
                JoinBattleHandler joinBattleHandler = applicationContext.getBean(JoinBattleHandler.class);
                framework.registerHandler(joinBattleHandler);
                
                LeaveBattleHandler leaveBattleHandler = applicationContext.getBean(LeaveBattleHandler.class);
                framework.registerHandler(leaveBattleHandler);
                
                StartBattleHandler startBattleHandler = applicationContext.getBean(StartBattleHandler.class);
                framework.registerHandler(startBattleHandler);
                
                BattleActionHandler battleActionHandler = applicationContext.getBean(BattleActionHandler.class);
                framework.registerHandler(battleActionHandler);
                
                BattleListHandler battleListHandler = applicationContext.getBean(BattleListHandler.class);
                framework.registerHandler(battleListHandler);
                
                PlayerStatusHandler playerStatusHandler = applicationContext.getBean(PlayerStatusHandler.class);
                framework.registerHandler(playerStatusHandler);
                
                logger.info("Initialized {} handlers for Scene Server from Spring context", framework.getHandlerManager().getHandlerCount());
            } else {
                logger.warn("ApplicationContext not available, using direct instantiation for handlers");
                // 降级方案：如果无法从容器获取，直接实例化（可能缺少依赖）
                framework.registerHandler(new CreateBattleHandler());
                framework.registerHandler(new JoinBattleHandler());
                framework.registerHandler(new LeaveBattleHandler());
                framework.registerHandler(new StartBattleHandler());
                framework.registerHandler(new BattleActionHandler());
                framework.registerHandler(new BattleListHandler());
                framework.registerHandler(new PlayerStatusHandler());
                
                logger.info("Initialized {} handlers for Scene Server using direct instantiation", framework.getHandlerManager().getHandlerCount());
            }
        } catch (Exception e) {
            logger.error("Error initializing Scene Server handlers", e);
            throw new RuntimeException("Failed to initialize Scene Server handlers", e);
        }
    }
    
    @Override
    protected void onConnectionActive(ChannelHandlerContext ctx) {
        super.onConnectionActive(ctx);
        // Scene Server特有的连接处理逻辑
        logger.debug("New scene connection from: {}", ctx.channel().remoteAddress());
    }
    
    @Override
    protected void onConnectionInactive(ChannelHandlerContext ctx) {
        super.onConnectionInactive(ctx);
        // Scene Server特有的连接关闭处理逻辑
        logger.debug("Scene connection closed from: {}", ctx.channel().remoteAddress());
    }
}